package com.zzzzzz.oms.orderMonitor;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zzzzzz.core.datagrid.BaseData;
import com.zzzzzz.plugins.shiro.I;
import com.zzzzzz.utils.BeanValidators;
import com.zzzzzz.utils.DateTimeUtils;

@Service
public class OrderMonitorService {
	@Resource
	public OrderMonitorDao orderMonitorDao;
	@Resource
	public Validator validator;
	
	@Transactional
	public int save(OrderMonitor orderMonitor, I i) {
		orderMonitor.setUpdDt(new Date());
		orderMonitor.setUpdBy(i.getId());
		if (orderMonitor.getId() == null) {
			orderMonitor.setAddDt(new Date());
			orderMonitor.setAddBy(i.getId());
			orderMonitorDao.add(orderMonitor);
		} else {
			orderMonitorDao.updById(orderMonitor);
		}

		return 1;
	}	
	
	@Transactional
	public BaseData batchAdd(List<OrderMonitor> list, I i) {
		logger.info("orderMonitor batchAdd validate start:" + DateTimeUtils.date2Str(new Date(), DateTimeUtils.FORMAT_YYYY_MM_DD_HH_MM_SS));
		//start validate
		int errTt = 0;
		StringBuilder errMsg = new StringBuilder();
		for (OrderMonitor orderMonitor : list) {
			try {
				BeanValidators.validateWithException(validator, orderMonitor);
			} catch (ConstraintViolationException e) {
				List<String> msgList = BeanValidators.extractPropertyAndMessageAsList(e, ": ");
				for (String msg : msgList) {
					errTt++;
					errMsg.append("<br/>").append(msg);
				}
			} catch (Exception e) {
				logger.warn("", e);
				errTt++;
				errMsg.append("<br/>验证失败：").append(e.getMessage());
			}
		}
		if(errTt > 0){
			errMsg.insert(0, "共有"+errTt+"笔记录验证失败：");
			return new BaseData("101", errMsg.toString());
		}
		logger.info("orderMonitor batchAdd validate end:" + DateTimeUtils.date2Str(new Date(), DateTimeUtils.FORMAT_YYYY_MM_DD_HH_MM_SS));
		logger.info("orderMonitor batchAdd save start:" + DateTimeUtils.date2Str(new Date(), DateTimeUtils.FORMAT_YYYY_MM_DD_HH_MM_SS));
		//state save
		int susTt = 0;
		for (OrderMonitor orderMonitor : list) {
			orderMonitor.setSt(0);
			save(orderMonitor, i);
			susTt++;
		}
		logger.info("orderMonitor batchAdd save end:" + DateTimeUtils.date2Str(new Date(), DateTimeUtils.FORMAT_YYYY_MM_DD_HH_MM_SS));
		return new BaseData("0", "共有"+susTt+"笔记录导入成功。");
	}

	private static final Logger logger = LoggerFactory.getLogger(OrderMonitor.class);
}
